package com.woniu.inlet.subcrible;

import com.rabbitmq.client.Channel;
import com.woniu.outlet.dao.ReliablePoMapper;
import com.woniu.outlet.po.ReliablePo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSenderImpl;

@Configuration
@Slf4j
public class MessageListener {

    @Value("${spring.mail.username}")
    private String sendPerson;

    @Autowired
    private JavaMailSenderImpl javaMailSender;

    @Autowired
    private ReliablePoMapper reliableMapper;


    @RabbitListener(queues = {"workMessage_queue"})
    public void getMessage(Message message, Channel channel) throws Exception{
        log.info("我一直监听workMessage_queue");
        //1.拿到消息 插入数据库  如果插入成功，证明是第一次消费，如果插入失败了 证明重复消费
        String email = new String(message.getBody());
        String messgeId = message.getMessageProperties().getCorrelationId();
        ReliablePo reliable = new ReliablePo();
        try {

            reliable.setMessageid(Integer.parseInt(messgeId));
            reliableMapper.insert(reliable);
        }catch (Exception ex){
            channel.basicReject(message.getMessageProperties().getDeliveryTag(),false);
        }
        try {
            //发送优惠券
            SimpleMailMessage  mailMessage = new SimpleMailMessage();
            mailMessage.setSubject("恭喜你，注册成功");
            mailMessage.setText("http://www.baidu.com，点击之后可以开始登录");
            mailMessage.setTo(email);    //收件人的邮箱
            mailMessage.setFrom(sendPerson);  //发件人的邮箱，和配置的username保持一致
            javaMailSender.send(mailMessage);
            channel.basicAck(message.getMessageProperties().getDeliveryTag(),true);
        }catch (Exception ex){
            channel.basicReject(message.getMessageProperties().getDeliveryTag(),true);
            //删除消息去重表的消息
            reliableMapper.deleteByPrimaryKey(reliable.getId());
        }
    }

}
